import React from 'react';
import { Table, Button, Modal, Form, Input, message, Space } from 'antd';
import { SlaveNode, NodeFormValues } from '../../types/device';

interface SlaveNodeManagementProps {
  slaveNodes: SlaveNode[];
  onAddNode: (node: SlaveNode) => void;
  onDeleteNode: (key: string) => void;
  isAddNodeModalVisible: boolean;
  setIsAddNodeModalVisible: (visible: boolean) => void;
  nodeForm: any;
}

const SlaveNodeManagement: React.FC<SlaveNodeManagementProps> = ({
  slaveNodes,
  onAddNode,
  onDeleteNode,
  isAddNodeModalVisible,
  setIsAddNodeModalVisible,
  nodeForm
}) => {
  // 从设备节点表格列定义
  const nodeColumns = [
    { title: '序号', dataIndex: 'index', key: 'index', render: (_: any, __: any, index: number) => index + 1 },
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '名称', dataIndex: 'name', key: 'name' },
    { title: '类型', dataIndex: 'type', key: 'type' },
    { title: '从机地址', dataIndex: 'slaveAddress', key: 'slaveAddress' },
    { title: '寄存器', dataIndex: 'register', key: 'register' },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: SlaveNode) => (
        <Space size="middle">
          <Button type="text" size="small">编辑</Button>
          <Button type="text" danger size="small" onClick={() => onDeleteNode(record.key)}>删除</Button>
        </Space>
      )
    }
  ];

  const handleAddNodeSubmit = async () => {
    try {
      const values = await nodeForm.validateFields();
      const newNode: SlaveNode = {
        key: `node-${Date.now()}`,
        id: `node-${Date.now()}`,
        name: values.name,
        type: '传感器', // 默认类型，可根据实际需求调整
        slaveAddress: values.slaveAddress,
        register: values.register,
        createTime: new Date().toISOString(),
      };
      onAddNode(newNode);
      message.success('从设备节点已添加');
      setIsAddNodeModalVisible(false);
      nodeForm.resetFields();
    } catch (error) {
      message.error('表单验证失败，请检查必填项');
    }
  };

  const handleCancelAddNode = () => {
    nodeForm.resetFields();
    setIsAddNodeModalVisible(false);
  };

  return (
    <>
      {/* 从设备节点表格 */}
      <Table
        columns={nodeColumns}
        dataSource={slaveNodes}
        rowKey="key"
        pagination={false}
        bordered
        title={() => (
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button type="primary" onClick={() => setIsAddNodeModalVisible(true)}>
              添加节点
            </Button>
          </div>
        )}
      />

      {/* 添加从设备节点模态框 */}
      <Modal
        title="添加从设备节点"
        open={isAddNodeModalVisible}
        onOk={handleAddNodeSubmit}
        onCancel={handleCancelAddNode}
        footer={[
          <Button key="cancel" onClick={handleCancelAddNode}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleAddNodeSubmit}>
            确定
          </Button>
        ]}
      >
        <Form
          form={nodeForm}
          layout="vertical"
          name="node_form"
        >
          <Form.Item
            name="name"
            label="节点名称"
            rules={[{ required: true, message: '请输入节点名称' }]}
          >
            <Input placeholder="请输入节点名称" />
          </Form.Item>
          
          <Form.Item
            name="slaveAddress"
            label="从机地址"
            rules={[{ required: true, message: '请输入从机地址' }]}
          >
            <Input placeholder="请输入从机地址" />
          </Form.Item>
          
          <Form.Item
            name="register"
            label="寄存器"
            rules={[{ required: true, message: '请输入寄存器' }]}
          >
            <Input placeholder="请输入寄存器" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default SlaveNodeManagement;